<?php
/**
 * Created by PhpStorm.
 * User: 江雪
 * Date: 2019/5/25
 * Time: 15:06
 */

namespace app\v2\controller;

use app\common\controller\Checking;
use app\common\controller\Email;
use app\common\controller\Sms;
use app\common\controller\Token;
use fast\Redis;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Request;

class Login extends Controller
{
    protected $params;
    protected $redis;
    protected $userId;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->params = input();
        $this->redis=Redis::getRedis();
        $jwt= $this->request->cookie('JAVASESSIONID');
        if ( !empty( $jwt ) ) {
            $data = Token::decode( $jwt );
            if ( $data['status'] != false ) {
                $user = $data['content'];
                if ( !empty( $user->token ) ) {
                    $this->redis=Redis::getRedis();
                    $jwtToken = $this->redis->get( 'jwtToken:' . $user->id );
                    if ( $jwtToken == $user->token ) {
                        $this->userId=$user->id;
                    }
                }
            }
        }
    }

    /**
     * 注册
     */
    public function doRegister()
    {
        $keys = 'account,code,password,repassword,invitationCode';
        if (!Checking::keyIsExistence($keys, $this->params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }

        if (!Checking::phoneRule($this->params['account'])) {
            if (!Checking::emailRule($this->params['account'])){
                Checking::response(-2, '请输入正确的手机/邮箱');
            }
        }

        if (!Checking::passwordRule($this->params['password'])) {
            Checking::response(-4, Checking::MESSAGE['passwordRule']);
        }

        if ($this->params['password'] != $this->params['repassword']) {
            Checking::response(-2, '两次输入密码不一致');
        }

        $model = Db::name('users');
        if (Checking::phoneRule($this->params['account'])) {
            if (Checking::accountIsMysql($this->params['account'], $model, 'phone')) {
                Checking::response(-7, Checking::MESSAGE['phoneIsMysql']);
            }
        }else if (Checking::emailRule($this->params['account'])){
            if (Checking::accountIsMysql($this->params['account'], $model, 'mailbox')) {
                Checking::response(-7, Checking::MESSAGE['emailIsMysql']);
            }
        }

        if (empty($this->params['invitationCode'])) {
//            $this->params['puid']=753508;
            Checking::response(-2, '请填写推荐人');
        }

        $pid = 1;
        if ($this->params['invitationCode']) {
            $where = [];
            $where['invite_code'] = $this->params['invitationCode'];
//            $where1['phone'] = $this->params['puid'];
//            $father = $model->whereOr( $where )->whereOr( $where1 )->field( 'id' )->find();
            $father = $model->whereOr($where)->field('id')->find();
            if (!$father) {
                Checking::response(-5, '推荐人有误');
            }
            $pid = $father['id'];
        }
        #判断验证码和手机号
//        if (Sms::confirmation($this->params['a'], $this->params['code'], 1)) {
//            Checking::response( -5, '验证码错误' );
//        }

        Db::startTrans();
        try {
            $codes = Checking::nonceStrByUnique('uuid', $model, 6, 2);
//        $codes= Checking::getRefereeId( 'uuid', $model);
//            do {
//                $token_address = makeStr('token_address', 42);
//            } while ($model->where(['token_address' => $token_address])->count());
//            $times = date('YmdHis');

            $insert = [
                'pid' => $pid,
                'password' => Checking::passwordHash(trim($this->params['password'])),
                'uuid' => $codes,
                'invite_code' => Checking::nonceStrByUnique('invite_code', $model, 6, 1),
                'headimg' => '/assets/img/head.png', //默认头像
                'create_time' => date('YmdHis')
            ];
            if (Checking::phoneRule($this->params['account'])) {
                $insert['phone']=$this->params['account'];
            }else if (Checking::emailRule($this->params['account'])){
                $insert['mailbox']=$this->params['account'];
            }

            if (!$insert['pid']) {
                Checking::response(-2, '请填写推荐人');
            }

            $newId = $model->insertGetId($insert);
            if ($newId) {
                if ($newId && $pid > 0) {
                    $position = db('users_position')
                        ->where(['user_id' => $pid])
                        ->field('pid,lay')
                        ->select();
                    $action = [];
                    if ($position) {
                        $action[0]['user_id'] = $newId;
                        $action[0]['pid'] = $pid;
                        $action[0]['lay'] = 1;
                        $action[0]['create_time'] = $insert['create_time'];
                        foreach ($position as $k => $v) {
                            $action[$k + 1]['user_id'] = $newId;
                            $action[$k + 1]['pid'] = $v['pid'];
                            $action[$k + 1]['lay'] = $v['lay'] + 1;
                            $action[$k + 1]['create_time'] = $insert['create_time'];
                        }
                        db('users_position')->insertAll($action);
                    } else {
                        $action['user_id'] = $newId;
                        $action['pid'] = $pid;
                        $action['lay'] = 1;
                        $action['create_time'] = $insert['create_time'];
                        db('users_position')->insert($action);
                    }
                }

//                $usdt_address=(new Coins())->usdtcoin($newId);

//                Db::name('users')->where(['id'=>$newId])->setField('token_address',$usdt_address);
                Db::name('users_asset')->insert(['user_id' => $newId]);
                Db::name('users_coin')->insert(['user_id' => $newId]);
                Db::name('users_legal')->insert(['user_id' => $newId]);
                Db::commit();
                Checking::response(200, '注册成功');
            }
            Checking::response(203, '注册失败');
        } catch (Exception $exception) {
            Db::rollback();
            Checking::response(-202, $exception->getMessage());
        }
    }

    /**
     * 登录
     */
    public function doLogin()
    {
        if (!Checking::keyIsExistence('account,password', $this->params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $where = [];
        if (!Checking::phoneRule($this->params['account'])) {
            $where['mailbox'] = $this->params['account'];
        } else {
            $where['phone'] = $this->params['account'];
        }
        if (!Checking::passwordRule($this->params['password'])) {
            Checking::response(-4, Checking::MESSAGE['passwordRule']);
        }

        $model = Db::name('users');
        $users = $model->where($where)->field('id,password,phone,status,nickname,uuid,headimg')->find();
        if (!$users) {
            Checking::response(-3, '账号/密码错误');
        }

        if (!Checking::checkPassword($users['password'], $this->params['password'])) {
            Checking::response(-5, Checking::MESSAGE['checkPassword']);
        }

        if ($users['status'] == 2) {
            Checking::response(-100, '账号被封,请联系管理员');
        }
        $data=[
            'id' => $users['id'],
            'uuid' => $users['uuid'],
            'phone' => $users['phone'],
            'nickname' => $users['nickname'],
            'headimg' => $users['headimg'],
            'token' => md5( time() . mt_rand( 1000, 9999 ) )
        ];
        $exprie = 24 * 60 * 60 * 7;
        $this->redis->setex( 'jwtToken:' . $users['id'], $exprie, $data['token'] );//请求接口时验证jwtToken是否相同,不相同则为错误
        $jwt = Token::encode( $data, $exprie );
        Cookie::set('JAVASESSIONID',$jwt);
        Checking::response(200, '登录成功', ['code' => $jwt]);
    }

    /**
     * 退出
     */
    public function logOut()
    {
        session(null);
        Checking::response(200, '退出成功');
    }


    /**
     * 忘记密码
     * @param $phone
     * @param $code
     * @param $password
     * @param $repassword
     * @return \think\response\Json
     */
    public function forgetLoginPwd()
    {

        if (!Checking::keyIsExistence('account,password,repassword', $this->params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        #再次确认密码
        if ($this->params['password'] != $this->params['repassword']) {
            Checking::response(-4, '两次输入密码不一致');
        }

        if (!Checking::passwordRule($this->params['password'])) {
            Checking::response(-4, Checking::MESSAGE['passwordRule']);
        }
        $data = [];
        $data['password'] = Checking::passwordHash($this->params['password']);
        $data['update_time'] = date('YmdHis');
        $model = Db::name('users');
        if (strpos($this->params['account'],'@') !==false){
            if (!Checking::accountIsMysql($this->params['account'], $model, 'mailbox')) {
                Checking::response(-2, '账号不存在');
            }
            #修改用户密码插入表中
            $result = $model->where(['mailbox' => $this->params['account']])->update($data);
        }else{
            if (!Checking::accountIsMysql($this->params['account'], $model, 'phone')) {
                Checking::response(-2, '账号不存在');
            }
            #判断验证码和手机号
//        if (Sms::confirmation($this->params['phone'], $this->params['code'], 6)) {
//            Checking::response(-5, '验证码错误');
//        }
            #修改用户密码插入表中
            $result = $model->where(['phone' => $this->params['account']])->update($data);
        }
        if ($result) {
            Checking::response(200, '修改成功');
        }
        Checking::response(-200, '修改失败');
    }

    /**
     * 发送验证码（短信）
     * @param string $phone 手机号
     * @param int $type (1注册，2设置二级密码,3修改二级密码,4修改登录密码,6忘记密码,7绑定钱包)
     */
    public function getSmsCode()
    {
        $params = input('param.');
        if (!Checking::keyIsExistence('type', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $userModel = Db::name('users');
        #注册
        if ($params['type'] == 1) {   //注册
            $phone = $params['phone'];
//            halt(Checking::phoneIsMysql( $phone, $userModel, 'phone' ));
            if (Checking::accountIsMysql($phone, $userModel, 'phone') > 0) {
                Checking::response(-2, Checking::MESSAGE['phoneIsMysql']);
            }
        } else if ($params['type'] == 6) {    //忘记密码
            $phone = $params['phone'];
            if (Checking::accountIsMysql($phone, $userModel, 'phone') <= 0) {
                Checking::response(-2, '请输入正确的手机号');
            }
        } else if ($params['type'] == 13) {    //忘记密码
            $phone = $params['phone'];
            if (Checking::accountIsMysql($phone, $userModel, 'phone') <= 0) {
                Checking::response(-2, '请输入正确的手机号');
            }
        } else {
            $phone = session('phone');
        }

        try {
            //修改密碼
            $uid = session('uid');

            if (in_array($params['type'], [2, 3, 4, 7])) {
                if (!$uid) {
                    throw new Exception('用户信息失效，请重新登录', -3);
                }

                if (!$userModel->where(['id' => $uid])->count()) {
                    throw new Exception('用户信息失效，请重新登录', -4);
                }
            }
            $result = Sms::reg_send($phone, $params['type']);
            if ($result['status'] !== -1 && $result['status'] != -2) {
                Checking::response(200, '发送成功');
            } else if ($result['status'] == -2) {
                throw new Exception('上次验证码还未失效!', -5);
            } else {
                throw new Exception('短信平台出错,发送失败!', -6);
            }
        } catch (Exception $e) {
            Checking::response($e->getCode(), $e->getMessage());
        }
    }


    /**
     * 发送验证码（邮箱）
     */
    public function getEmsCode(){
        $params = input('param.');
        if (!Checking::keyIsExistence('type', $params)) {
            Checking::response(-1, Checking::MESSAGE['keyIsExistence']);
        }
        $userModel = Db::name('users');
        #注册
        if ($params['type'] == 1) {   //注册
            $email = $params['account'];
            if (Checking::accountIsMysql($email, $userModel, 'mailbox') > 0) {
                Checking::response(-2, Checking::MESSAGE['phoneIsMysql']);
            }
        } else if ($params['type'] == 6) {    //忘记密码
            $email = $params['account'];
            if (Checking::accountIsMysql($email, $userModel, 'mailbox') <= 0) {
                Checking::response(-2, '请输入正确的手机号');
            }
        } else if ($params['type'] == 13) {    //忘记密码
            $email = $params['account'];
            if (Checking::accountIsMysql($email, $userModel, 'mailbox') <= 0) {
                Checking::response(-2, '请输入正确的手机号');
            }
        } else {
            $email=Db::name('users')->where(['id'=>$this->userId])->value('mailbox');
        }
        try {
            //修改密碼
            $uid = $this->userId;
            if (in_array($params['type'], [2, 3, 4, 7])) {
                if (!$uid) {
                    throw new Exception('用户信息失效，请重新登录', -3);
                }
                if (!$userModel->where(['id' => $uid])->count()) {
                    throw new Exception('用户信息失效，请重新登录', -4);
                }
            }
            $result = Email::sendEmail($email, $params['type']);
            if ($result['status'] != 200) {
                throw new Exception($result['message'], -4);
            }
            Checking::response(200,'发送成功');
        } catch (Exception $e) {
            Checking::response($e->getCode(), $e->getMessage());
        }

    }
    /**
     * 通用翻译接口
     */
//    public function setLang()
//    {
//        $param = Request::instance()->only('lang,msg');
//        if (empty($param['lang'])) {
//            $param['lang'] = 'zh';
//        }
//        if (empty($param['msg'])) {
//            Checking::response(-208, '请填写要翻译的语言');
//        }
//
//        $res = Checking::getTrueLang($param['msg'], $param['lang']);
//        Checking::response(200, 'ok', $res);
//    }
//    public function test()
//    {
//        $url = 'https://mainnet.infura.io/v3/1a1b389f318b41608ed75159d77f2ff2';
//        $param = ['jsonrpc'=>'2.0','method'=>'personal_newAccount','params'=>['eth_pass'],'id'=>1];
//        $res = $this->http_put_data_ada($url,json_encode($param));
//        dd($res);
//
//    }

//    public function http_put_data_ada($url, $data)
//    {
//        $data = json_encode($data);
//        $ch = curl_init(); //初始化CURL句柄
//        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
//        curl_setopt($ch, CURLOPT_HTTPHEADER, [
//                "Content-Type: application/json; charset=utf-8",
//            ]
//        );
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); //设置请求方式
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
//        ob_start();
//        curl_exec($ch);
//        $return_content = ob_get_contents();
//        ob_end_clean();
//        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        return [$return_code, $return_content];
//    }
}